package com.favccxx.search.infrastructure.interceptor;

import com.favccxx.search.domain.auditlog.AuditLog;
import com.favccxx.search.domain.auditlog.AuditLogRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @author favccxx
 * @date 5/13/2020 4:20 PM
 */
@Component
public class AuditLogInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    AuditLogRepo auditLogRepo;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        AuditLog auditLog = new AuditLog();
        auditLog.setMethod(request.getMethod());
        auditLog.setPath(request.getRequestURI());

        auditLog.setUsername("Audit");
        auditLogRepo.save(auditLog);

        request.setAttribute("auditLogId", auditLog.getId());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String auditLogId = (String) request.getAttribute("auditLogId");
        Optional<AuditLog> opt = auditLogRepo.findById(auditLogId);
        if (opt.isPresent()) {
            AuditLog auditLog = opt.get();
            auditLog.setStatus(response.getStatus());
            auditLogRepo.save(auditLog);
        }
    }
}
